package com.book.framework.web.service;

import cn.hutool.core.util.DesensitizedUtil;
import com.book.common.constant.CacheConstants;
import com.book.common.constant.UserConstants;
import com.book.common.core.domain.entity.AppUser;
import com.book.common.core.redis.RedisCache;
import com.book.common.exception.ServiceException;
import com.book.common.utils.DateUtils;
import com.book.common.utils.SecurityUtils;
import com.book.common.utils.StringUtils;
import com.book.system.domain.param.AppUserRegisterParam;
import com.book.system.service.IAppUserService;
import org.springframework.stereotype.Component;

/**
 * @author Bigboss
 * @create 2024-10-19 16:44
 */
@Component
public class AppRegisterService {

    private final IAppUserService appUserService;

    private final RedisCache redisCache;

    public AppRegisterService(IAppUserService appUserService, RedisCache redisCache) {
        this.appUserService = appUserService;
        this.redisCache = redisCache;
    }


    /**
     * 注册
     */
    public String register(AppUserRegisterParam registerBody) {
        String msg = "", username = registerBody.getPhone(), password = registerBody.getPassword();
        AppUser appUser = new AppUser();
        appUser.setPhone(username);

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (StringUtils.isEmpty(registerBody.getCode())) {
            msg = "验证码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (!appUserService.checkPhoneUnique(appUser)) {
            msg = "注册用户'" + username + "'失败，手机号已存在";
        }else {
            //校验手机验证码
            validateCaptcha(username,registerBody.getCode());
            appUser.setNickName(DesensitizedUtil.mobilePhone(username));
            appUser.setPassword(SecurityUtils.encryptPassword(password));
            appUser.setRegisterTime(DateUtils.getNowDate());
            appUser.setCreateBy("self");
            appUser.setCreateTime(DateUtils.getNowDate());
            boolean regFlag = appUserService.save(appUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            }
        }
        return msg;
    }

    /**
     * 校验手机验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @return 结果
     */
    public void validateCaptcha(String username, String code) {
        String redisCode = redisCache.getCacheObject(CacheConstants.PHONE_CODE_KEY + username);
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            throw new ServiceException("验证码不存在或错误");
        }
    }
}
